<template>
  <div>
    <el-form
      class="input-form"
      label-position="right"
      label-width="120px"
      ref="editForm"
      :rules="propRules"
      :disabled="propReadonly"
      :model="form"
    >
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="科室名称" prop="deptId">
            <el-select v-model="form.deptId" filterable disabled>
              <el-option value>请选择</el-option>
              <el-option v-for="dict in propDictionaries['deptId'] || []" :key="dict.id" :label="dict.name" :value="dict.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所属试剂组" prop="reagentTeamId">
            <el-select v-model="form.reagentTeamId" @change="onReagentTeamChange" :disabled="form.id != null">
              <el-option v-for="dict in getReagentTeam" :key="dict.id" :label="dict.name" :value="dict.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="消耗类型" prop="useType">
            <el-select v-model="form.useType" filterable @change="onUseTypeChange">
              <el-option v-for="dict in utils.getDictDataList('use_reagent_type') || []" :key="dict.value" :label="dict.label"
                :value="dict.value" v-show="dict.value != 'DIST'"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="取用人" prop="user">
            <el-input v-model="form.user" disabled/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="检验设备" prop="equipmentCode">
            <FortenDataviewDown
              ref="inspSelect"
              propFieldText="equipmentName"
              propDownType="form"
              propCheckType="radio"
              :propForm="form"
              :propTableQueries="$newWrapper().eq('reagent_team_id', form.reagentTeamId || '-1').eq('flagTesting', 1)"
              :propUserParam="{viewKey: 'base_inspection_equipment_select',
                useMsg: '数据筛选条件:查询所属试剂组的检验设备信息',
                reagentTeamId: form.reagentTeamId
              }"
              @select-change="selectInspChange"
            ></FortenDataviewDown>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="form.flowStatus == null || form.flowStatus == 'start' ">
          <el-form-item label="扫描条码" prop="txtScan" id="txtScan">
            <el-input v-model="txtScan" ref="scanDom" placeholder="在此设置光标，开始扫描检验设备条码或试剂条码" 
              style="width:80%;float:left;margin-right:10px;" @keyup.native.enter="barCodeScan" />
            <FortenDataviewDown
              ref="reagentSelect"
              propDownType="form"
              :propFlagDialog="true"
              propCheckType="checkbox"
              propClickType="button"
              propClickTitle="选择试剂"
              :propUserParam="{viewKey: 'wm_tertiary_stock_select',
                useMsg: '数据筛选条件:查询所属试剂专业组的试剂数据',
                reagentTeamId: form.reagentTeamId
              }"
              :propTableQueries="$newWrapper().eq('reagent_team_id', form.reagentTeamId || '-1').gt('packageQty', 0)"
              @select-change="selectReagentChange"
            ></FortenDataviewDown>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" :autosize="{ minRows: 1, maxRows: 4}" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <div style="height: 500px; overflow: auto">
          <data-view
            propViewKey="dept_use_reagent_dtl"
            :propInitData="form"
            ref="childDataView"
            :propHidePageSearch="true"
            :propHideQueryButton="true"
            :propParentPage="_self"
            :propAutoFetchData="false"
            @extra-button-click="handleExtraClick"
          />
        </div>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import barcodeParse from '@/util/barcodeParse'

export default {
  data() {
    return {
      form: {},
      viewData: {},
      txtScan: '',
      stockIds: [],
      reagentTeamList: [],
      reagentDialogVisible: false
    }
  },
  methods: {
    getChildViewQueryWrapper() {
      if (this.form.id) {
        return this.$newWrapper().eq('id', this.form.id)
      } else {
        return this.$newWrapper().ne(1, 1)
      }
    },
    getChildRows() {
      if (!this.$refs.childDataView) {
        return []
      }
      return this.$refs.childDataView.getRows0()
    },
    getReagentTeamList() {
      this.$ajax('/base/reagent_team/currentTeam').then(resp => {
        if (resp.code == 0) {
          this.reagentTeamList = resp.data || []
          if (this.reagentTeamList.length == 1) {
            // 如果当前用户只属于一个专业组，则默认第一个专业组
            this.$set(this.form, 'reagentTeamId', this.reagentTeamList[0].id)
          }
        }
      })
    },
    //扫码SN或RFID
    barCodeScan() {
      if (!this.form.reagentTeamId) {
        this.txtScan = ''
        this.utilMessage.error('请选择所属试剂组')
        return
      }
      let codeType = barcodeParse.barCodeType(this.txtScan)

      if (this.form.useType == 'EQUIPMENT' || codeType == 'GTIN') {
        // 是否检验设备
        this.getINS(this.txtScan, codeType)
      } else if (codeType == 'SN' || codeType == 'RFID') {
        this.getByCode(this.txtScan, codeType)
      } else {
        this.utilMessage.warning('请扫描有效的条码')
        window.scanError()
        return
      }
      this.txtScan = ''
    },
    getByCode(code, codeType) {
      if (this.form.useType == 'EQUIPMENT' && !this.form.equipmentCode) {
        this.utilMessage.error('请先扫描检验设备编码')
        return
      }
      let wrapper = this.$newWrapper().eq(codeType.toLowerCase(), code).gt('packageQty', 0)
      let params = {
        queryString: JSON.stringify(wrapper.queryConditions),
      }
      this.$ajax.get('/wm/tertiary_stock/list', { params }).then((resp) => {
        if (resp.data.length === 0) {
          this.utilMessage.error('请扫描有效的试剂条码')
          return
        }
        let stock = resp.data[0]
        if (this.form.reagentTeamId != stock.reagentTeamId) {
          this.txtScan = ''
          this.utilMessage.error('扫描的试剂不属于当前试剂组，不能进行消耗')
        } else {
          this.getItem([{stockId: stock.id, sn: code}])
        }
      })
    },
    getINS(code, codeType) {
      let wrapper = this.$newWrapper().eq('sn', code)
      let params = {
        queryString: JSON.stringify(wrapper.queryConditions),
      }
      this.$ajax.get('/base/inspection_equipment/list', { params }).then((resp) => {        
        if (resp.data.length === 0) {
          if (codeType == 'SN' || codeType == 'RFID') {
            this.getByCode(code, codeType)
          } else {
            this.utilMessage.warning('请扫描有效的检验设备编码或试剂条码')
          }
          return
        }

        const ins = resp.data[0]
        if (this.form.reagentTeamId != ins.reagentTeamId) {
          this.txtScan = ''
          this.utilMessage.error('扫描的检验设备不属于当前试剂组，不能进行消耗')
        } else if (!ins.flagTesting) {
          this.txtScan = ''
          this.utilMessage.error('扫描的设备不是试剂检验设备，请重新扫描')
        } else {
          if (this.form.equipmentCode && this.form.equipmentCode != ins.code) {
            this.clearForm()
          }
          this.$set(this.form, 'equipmentCode', ins.code)
          this.$set(this.form, 'equipmentName', ins.name)
          const find = (this.utils.getDictDataList('use_reagent_type') || []).find(a => a.value == 'EQUIPMENT')
          this.$set(this.form, 'useType', 'EQUIPMENT')
          this.$set(this.form, 'useTypeName', find.name || '')
        }
      })
    },
    async getItem(items) {
      if (this.$refs.childDataView.getRows() && this.$refs.childDataView.getRows().length > 0) {
        const exist = this.$refs.childDataView.getRows().filter(r => items.some(i => i.sn == r.sn))
        if (exist) {
          // 同样的sn再扫一次，直接删除
          this.$refs.childDataView.ocRemoveRows(exist)
          this.stockIds = this.stockIds.filter(id => !exist.some(e => e.stockId == id))
          // items = items.filter(i => !exist.some(e => e.sn == i.sn))
          if (items.length == 0) return
        }
      }

      const params = {
        form: {
          useType: this.form.useType,
          deptId: this.form.deptId,
          reagentTeamId: this.form.reagentTeamId,
          reagentTeamName: this.form.reagentTeamName,
          equipmentCode: this.form.equipmentCode || ''
        },
        stockIds: items.map(i => i.stockId)
      }
      await this.$ajax.post('/dept/use_reagent/getBySns', params).then((resp) => {
        if (resp.code == 0 && resp.data) {
          this.txtScan = ''
          resp.data.map(data => { return {...data, id: data.matrId + '|' + data.sn} }).forEach(data => {
            this.$refs.childDataView.ocInsertNewRow(data)
          })
          this.stockIds.push(...params.stockIds)
        }
      })
    },
    whfilter() {
      this.searchedList = this.warehouseList.filter(item => item.name.indexOf(this.form.reagentTeamName) > -1
        || this.pyutils.chineseToPinYin(item.name).indexOf(this.form.reagentTeamName) > -1)
    },
    handleExtraClick({button, data}) {
      if (button.key == 'del') {
        if (data && data.length > 0) {
          this.$refs.childDataView.ocRemoveRows(data)
          this.stockIds = this.stockIds.filter(id => !data.some(d => d.stockId == id))
        }
      }
      this.utilVue.loadHide()
    },
    selectInspChange({row}) {
      const insp = row
      if (this.form.useType != 'EQUIPMENT') {
        this.utilMessage.warning('当前选择的消耗类型不需要扫描检验设备')
        return
      }
      if (insp) {
        this.$set(this.form, 'equipmentCode', insp.code)
        this.$set(this.form, 'equipmentName', insp.name)
      }
    },
    selectReagentChange({rows}) {
      if (rows && rows.length > 0) {
        this.txtScan = ''
        this.getItem(rows.map(row => { return { stockId: row.id, sn: row.sn } }))
      }
    },
    handleSubmit() {
      this.$confirm('确定要提交试剂消耗列表吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        const items = this.$refs.childDataView.rows
        if (this.$refs.childDataView.rows.length == 0) {
          this.utilMessage.error('消耗明细不能为空，请扫描试剂SN/RFID')
          return
        }

        items.forEach(item => { 
          item.useType = this.form.useType
          item.remark = this.form.remark
          item.id = undefined
        })
        const params = {
          stockIds: this.stockIds,
          items
        }
        this.$ajax.post('/dept/use_reagent/saveItems', params).then((resp) => {
          if (resp.code == 0) {
            this.utilMessage.success('试剂消耗成功')
            this.clearForm()
          }
        })
      })
    },
    clearForm() {
      this.$refs.childDataView.ocRemoveAllRows(true)
      this.stockIds = []
      this.txtScan = ''
      this.form.remark = ''
      this.$refs.scanDom && this.$refs.scanDom.focus()
    },
    onUseTypeChange() {
      this.clearForm()
    },
    onReagentTeamChange() {
      this.$set(this.form, 'equipmentCode', '')
      this.$set(this.form, 'equipmentName', '')
    }
  },
  created() {
    const that = this
    this.$emit('event-register', {
      validate: (callback) => {
        this.$refs.editForm.validate(callback)
      },
      beforeSave: () => {
        this.$emit('data-callback', this.form)
        return true
      },
      afterMove: async (formData, initData) => {
        this.form = global.utils.jsonClone(formData)
        // 新增，设置默认值
        if (!this.form.id) {
          this.$set(this.form, 'user', this.utils.getCurrentUser().name)
          this.$set(this.form, 'deptId', this.utils.getCurrentUser().officeId)
          if (this.form.deptId) {
            if (!this.propDictionaries.deptId.find(dp => dp.id == this.form.deptId)) {
              this.utilMessage.error('您所在的科室不是业务科室，不能消耗试剂')
              this.$set(this.form, 'deptId', '')
              this.$emit('hide-form-button')
            }
          }
          this.$set(this.form, 'useType', 'MANUAL')
          const find = (this.utils.getDictDataList('use_reagent_type') || []).find(a => a.value == 'MANUAL')
          this.$set(this.form, 'useTypeName', find.name || '')
        } else {
          // 隐藏删除按钮
          const button = this.$refs.childDataView.$el.getElementsByClassName('vxe-grid--toolbar-wrapper')
          if (button) {
            button[0].style.visibility = 'hidden'
          }
          let newWrapper = this.$newWrapper().eq('id', this.form.id)
          this.$refs.childDataView.setQueryWrapper(newWrapper)
        }
        await this.getReagentTeamList()
      },
      afterSave: () => { },
      beforeDelete: () => {
        return true
      },
      afterDelete: () => {
      },
      beforeFlow: (flowButtonKey) => {
        return true
      },
      afterFlow: (flowButtonKey) => {
      },
      beforeClose: () => {
        return true
      },
      afterClick(button, data, viewForm) {
        const { key: buttonKey } = button
        if (buttonKey == 'tijiao') {
          that.handleSubmit()
        }
      }
    })
  },
  mounted() {
    this.$refs.scanDom.focus()
  },
  props: {
    propParent: Object,
    propInitData: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object
  },
  components: {
  },
  computed: {
    cpChildRows() {
      if (!this.$refs.childDataView) {
        return []
      }
      return this.$refs.childDataView.getRows0()
    },
    getReagentTeam() {
      if (this.form.id != null) {
        return this.propDictionaries.reagentTeamId || []
      }
      return this.reagentTeamList
    }
  },
  watch: {

  }
}
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
}
</style>
